<template>
  <div class="app-container">
    <!-- 搜索区域 -->
    <el-card class="search-wrapper">
      <el-form :inline="true" :model="queryParams" @keyup.enter="handleQuery">
        <el-form-item label="规则名称">
          <el-input
            v-model="queryParams.ruleName"
            placeholder="请输入规则名称"
            clearable
            @clear="handleQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button type="success" @click="handleAdd">新增</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 数据表格 -->
    <el-card class="table-wrapper">
      <el-table v-loading="loading" :data="ruleList">
        <el-table-column type="index" label="序号" width="60" />
        <el-table-column prop="ruleName" label="规则名称" />
        <el-table-column prop="workTime" label="上班时间" width="100" />
        <el-table-column prop="offTime" label="下班时间" width="100" />
        <el-table-column prop="lateMinutes" label="迟到判定(分钟)" width="120" />
        <el-table-column prop="earlyMinutes" label="早退判定(分钟)" width="120" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-switch
              v-model="row.status"
              :active-value="1"
              :inactive-value="0"
              @change="handleStatusChange(row)"
            />
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link @click="handleEdit(row)">编辑</el-button>
            <el-button type="danger" link @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="queryParams.pageNum"
          v-model:page-size="queryParams.pageSize"
          :total="total"
          :page-sizes="[10, 20, 30, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新增/编辑弹窗 -->
    <el-dialog
      :title="dialog.title"
      v-model="dialog.visible"
      width="500px"
      @close="handleDialogClose"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="规则名称" prop="ruleName">
          <el-input v-model="form.ruleName" placeholder="请输入规则名称" />
        </el-form-item>
        <el-form-item label="上班时间" prop="workTime">
          <el-time-picker
            v-model="form.workTime"
            format="HH:mm:ss"
            value-format="HH:mm:ss"
            placeholder="请选择上班时间"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="下班时间" prop="offTime">
          <el-time-picker
            v-model="form.offTime"
            format="HH:mm:ss"
            value-format="HH:mm:ss"
            placeholder="请选择下班时间"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="迟到判定" prop="lateMinutes">
          <el-input-number
            v-model="form.lateMinutes"
            :min="0"
            placeholder="请输入迟到判定分钟"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="早退判定" prop="earlyMinutes">
          <el-input-number
            v-model="form.earlyMinutes"
            :min="0"
            placeholder="请输入早退判定分钟"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-switch
            v-model="form.status"
            :active-value="1"
            :inactive-value="0"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialog.visible = false">取 消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
          确 定
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  pageRules,
  createRule,
  updateRule,
  deleteRule,
  updateRuleStatus
} from '@/api/attRule'

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  ruleName: ''
})

// 数据列表
const ruleList = ref([])
const total = ref(0)
const loading = ref(false)

// 弹窗控制
const dialog = reactive({
  visible: false,
  title: ''
})

// 表单对象
const formRef = ref(null)
const form = reactive({
  id: undefined,
  ruleName: '',
  workTime: '',
  offTime: '',
  lateMinutes: 0,
  earlyMinutes: 0,
  status: 1
})

// 表单校验规则
const rules = {
  ruleName: [
    { required: true, message: '请输入规则名称', trigger: 'blur' }
  ],
  workTime: [
    { required: true, message: '请选择上班时间', trigger: 'change' }
  ],
  offTime: [
    { required: true, message: '请选择下班时间', trigger: 'change' }
  ]
}

// 提交loading
const submitLoading = ref(false)

// 查询列表
const getList = async () => {
  loading.value = true
  try {
    const { data } = await pageRules(queryParams)
    ruleList.value = data.records
    total.value = data.total
  } catch (error) {
    console.error(error)
  } finally {
    loading.value = false
  }
}

// 查询按钮
const handleQuery = () => {
  queryParams.pageNum = 1
  getList()
}

// 新增按钮
const handleAdd = () => {
  dialog.title = '新增考勤规则'
  dialog.visible = true
  Object.assign(form, {
    id: undefined,
    ruleName: '',
    workTime: '',
    offTime: '',
    lateMinutes: 0,
    earlyMinutes: 0,
    status: 1
  })
}

// 编辑按钮
const handleEdit = (row) => {
  dialog.title = '编辑考勤规则'
  dialog.visible = true
  // 直接使用后端返回的时间字符串
  Object.assign(form, { ...row })
}

// 删除按钮
const handleDelete = (row) => {
  ElMessageBox.confirm('确认要删除该考勤规则吗？', '警告', {
    type: 'warning'
  }).then(async () => {
    try {
      await deleteRule(row.id)
      ElMessage.success('删除成功')
      getList()
    } catch (error) {
      console.error(error)
    }
  })
}

// 状态切换
const handleStatusChange = async (row) => {
  try {
    await updateRuleStatus(row.id, row.status)
    ElMessage.success('状态更新成功')
  } catch (error) {
    row.status = row.status === 1 ? 0 : 1
    console.error(error)
  }
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  await formRef.value.validate(async (valid) => {
    if (valid) {
      submitLoading.value = true
      try {
        // 直接提交表单数据，因为时间已经是正确的格式
        if (form.id) {
          await updateRule(form)
          ElMessage.success('更新成功')
        } else {
          await createRule(form)
          ElMessage.success('创建成功')
        }
        dialog.visible = false
        getList()
      } catch (error) {
        console.error(error)
      } finally {
        submitLoading.value = false
      }
    }
  })
}

// 弹窗关闭
const handleDialogClose = () => {
  if (formRef.value) {
    formRef.value.resetFields()
  }
}

// 分页大小改变
const handleSizeChange = (val) => {
  queryParams.pageSize = val
  getList()
}

// 页码改变
const handleCurrentChange = (val) => {
  queryParams.pageNum = val
  getList()
}

// 初始化
onMounted(() => {
  getList()
})
</script>

<style scoped>
.app-container {
  min-width: 850px;
}

.search-wrapper {
  margin-bottom: 20px;
}

.table-wrapper {
  .el-table {
    width: 100%;
    overflow-x: auto;
  }
}

.pagination-wrapper {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style> 